#!/usr/bin/env python
################################################################################
#            __  __            _   ____        _ _ ____        _              #
#           |  \/  | ___  __ _| |_| __ )  __ _| | | __ )  ___ | |_           #
#           | |\/| |/ _ \/ _` | __|  _ \ / _` | | |  _ \ / _ \| __|         #
#           | |  | |  __/ (_| | |_| |_) | (_| | | | |_) | (_) | |_          #
#           |_|  |_|\___|\__,_|\__|____/ \__,_|_|_|____/ \___/ \__|          #
#                                                                             #
#                                     by                                       #
# _______ .______       _______  _______   ______   ______   _______   _______  #
#|   ____||   _  \     |   ____||   ____| /      | /  __  \ |       \ |   ____|  #
#|  |__   |  |_)  |    |  |__   |  |__   |  ,----'|  |  |  ||  .--.  ||  |__      #
#|   __|  |      /     |   __|  |   __|  |  |     |  |  |  ||  |  |  ||   __|      #
#|  |     |  |\  \----.|  |____ |  |____ |  `----.|  `--'  ||  '--'  ||  |____      #
#|__|     | _| `._____||_______||_______| \______| \______/ |_______/ |_______|    #
#                                                                                 #
#                       Bot Administration Core-Module                           #
#                             Modular FrameWork                                 #
#
# Coders
#
#	Justin Giorgi (rebel_kid)
#
# Debuggers
#
#	Justin Giorgi (rebel_kid)
#	Lachlan Gilmour (chilli0)
#	David Liedle (spiderbyte)
#	(Polarina)
#	(prologic)
#
################################################################################
#                                                                              #
#                               GPL Licensed                                   #
#                                                                              #
################################################################################

# Imports
import time
import sys
import glob
		
# Exits the bot		
def allquit(globalvars, msgvars):

	# Checks for permissions
	if msgvars["botadmin"]:
	
		# Quits all servers
		for item in globalvars["servers"]:
			if len(msgvars["command"]) > 1:
				item.quit(' '.join(msgvars["command"][1:]))
			else:
				item.quit("MeatBallBot has been instructed to quit by a bot admin.")
		sys.exit()
		
	# Replies not authorized
	else:
		msgvars["server"].privmsg(msgvars["destination"], "Sorry but you're not allowed to do that.")

# Loads modules
def loadmodule(globalvars, msgvars):

	# Checks for permissions
	if msgvars["botadmin"]:

		# Checks length of command
		if len(msgvars["command"]) > 1:
	
			# Checks if the module request is a valid module and imports it
			modules = glob.glob('/opt/mbb/bin/*.py')
			if '/opt/mbb/bin/%s.py' % (msgvars["command"][1].lower()) in modules:
			
				# Checks if module is already loaded
				if msgvars["command"][1].lower() in sys.modules.keys():
					msgvars["server"].privmsg(msgvars["destination"], "That has already been loaded. Try reloading instead.")
				
				# Imports module
				else:
					mymod = __import__(msgvars["command"][1].lower())
					loaded = mymod.load(globalvars, msgvars)
					if loaded:
						msgvars["server"].privmsg(msgvars["destination"], "%s has expanded my tiny brain." %(msgvars["command"][1]))
					
			# Replies not a valid module
			else:
				msgvars["server"].privmsg(msgvars["destination"], "%s isn't there." % (msgvars["command"][1]))
				
		# Replies not enough info
		else:
			msgvars["server"].privmsg(msgvars["destination"], "More info plzkthnxbia")
			
	# Replies no permissions
	else:
		msgvars["server"].privmsg(msgvars["destination"], "Sorry but you're not allowed to do that.")

# Restarts the system			
def restart(globalvars, msgvars):

	# Checks for permissions
	if msgvars["botadmin"]:

		# Quits all servers
		if len(msgvars["command"]) > 1:
			for item in globalvars["servers"]:
				item.quit(' '.join(msgvars["command"][1:]))
		else:
			for item in globalvars["servers"]:
				item.quit("MeatBallBot has been instructed to restart by a bot admin.")
	
		# Clears server connections
		globalvars["servers"] = []

		# Restarts connection after a pause
		time.sleep(3)
		globalvars["connect"]()

	# Replies not authorized
	else:
		msgvars["server"].privmsg(msgvars["destination"], "Sorry but you're not allowed to do that.")
		
# Unloads modules
def reloadmodule(globalvars, msgvars):

	# Checks for permissions
	if msgvars["botadmin"]:

		# Checks length of command
		if len(msgvars["command"]) > 1:
	
			# Checks if the module request is a valid module and imports it
			modules = glob.glob('/opt/mbb/bin/*.py')
			if '/opt/mbb/bin/%s.py' % (msgvars["command"][1].lower()) in modules:
			
				# Checks if module is already loaded and reloads
				if msgvars["command"][1].lower() in sys.modules.keys():
					mymod = __import__(msgvars["command"][1].lower())
					mymod.unload(globalvars, msgvars, True)
					reload(mymod)
					mymod.load(globalvars, msgvars)
					msgvars["server"].privmsg(msgvars["destination"], "%s has expanded my tiny brain... again" %(msgvars["command"][1]))
				
				# Replies not loaded
				else:
					msgvars["server"].privmsg(msgvars["destination"], "That hasn't been loaded.")
					
			# Replies not a valid module
			else:
				msgvars["server"].privmsg(msgvars["destination"], "%s isn't there." % (msgvars["command"][1]))
				
		# Replies not enough info
		else:
			msgvars["server"].privmsg(msgvars["destination"], "More info plzkthnxbia")
			
	# Replies no permissions
	else:
		msgvars["server"].privmsg(msgvars["destination"], "Sorry but you're not allowed to do that.")
		
# Unloads modules
def unloadmodule(globalvars, msgvars):

	# Checks for permissions
	if msgvars["botadmin"]:

		# Checks length of command
		if len(msgvars["command"]) > 1:
	
			# Checks if the module request is a valid module and imports it
			modules = glob.glob('/opt/mbb/bin/*.py')
			if '/opt/mbb/bin/%s.py' % (msgvars["command"][1].lower()) in modules:
			
				# Checks if module is already loaded and unloads
				if msgvars["command"][1].lower() in sys.modules.keys():
					mymod = __import__(msgvars["command"][1].lower())
					unloaded = mymod.unload(globalvars, msgvars)
					if unloaded:
						msgvars["server"].privmsg(msgvars["destination"], "%s has been forgotten." %(msgvars["command"][1]))
				
				# Replies not loaded
				else:
					msgvars["server"].privmsg(msgvars["destination"], "That hasn't already been loaded.")
					
			# Replies not a valid module
			else:
				msgvars["server"].privmsg(msgvars["destination"], "%s isn't there." % (msgvars["command"][1]))
				
		# Replies not enough info
		else:
			msgvars["server"].privmsg(msgvars["destination"], "More info plzkthnxbia")
			
	# Replies no permissions
	else:
		msgvars["server"].privmsg(msgvars["destination"], "Sorry but you're not allowed to do that.")

# Sends a message to all channels		
def wallop(globalvars, msgvars):

	# Checks for permissions
	if msgvars["botadmin"]:

		# Sends message to all channels
		globalvars["cursor"].execute("select channame, netid from channels")
		data = globalvars["cursor"].fetchall()
		for row in data:
			net = globalvars["servers"][row[1] - 1]
			net.privmsg(row[0], ' '.join(msgvars["command"][1:]))
		
	# Replies not authorized
	else:
		msgvars["server"].privmsg(msgvars["destination"], "Sorry but you're not allowed to do that.")
		
def autoload(globalvars):
	
	# Loads oncall functions
	oncall = {'quit':allquit, 'load':loadmodule, 'restart':restart, 'reload':reloadmodule, 'unload':unloadmodule, 'wallop':wallop}
	for feature in oncall.items():
		if feature[0] not in globalvars["oncall"].keys():
			globalvars["oncall"][feature[0]] = feature[1]
	
def load(globalvars, msgvars):
	
	# Loads oncall functions
	oncall = {'quit':allquit, 'load':loadmodule, 'restart':restart, 'reload':reloadmodule, 'unload':unloadmodule, 'wallop':wallop}
	for feature in oncall.items():
		if feature[0] not in globalvars["oncall"].keys():
			globalvars["oncall"][feature[0]] = feature[1]
		else:
			msgvars["server"].privmsg(msgvars["destination"], "There is already a function named %s." % (feature[0]))
	return True
			
def unload(globalvars, msgvars, reloadmodule = False):
	
	# Unloads oncall functions
	if reloadmodule:
		oncall = {'quit':allquit, 'load':loadmodule, 'restart':restart, 'reload':reloadmodule, 'unload':unloadmodule, 'wallop':wallop}
		for feature in oncall.items():
			if feature[0] in globalvars["oncall"].keys():
				del globalvars["oncall"][feature[0]]
		return True
	else:
		msgvars["server"].privmsg(msgvars["destination"], "You want to unload my what?!?! How bout I just remove your liver.")
		return False
